﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Jamhee.Noctiluca.Common;

namespace Jamhee.Noctiluca.WebServer
{
    public abstract class WebResponser : IWebResponser
    {
        private const int BUFFER_LEN = 1024;

        public virtual void SendResponse(HttpListenerContext context, IWebConfiguration webConfig)
        {
            HttpListenerRequest request = context.Request;

            string websiteRoot = webConfig.GetWebsiteRootPath();
            string serverPath = ParseRequestURL(request.Url, webConfig);

            LogUtil.PrintInfo("Reqest URL: " + request.Url.AbsolutePath);
            LogUtil.PrintInfo("Local Server Path: " + serverPath);

            if (serverPath != null)
            {
                ParseRequestDocument(serverPath, context, webConfig);
            }
        }

        public virtual string ParseRequestURL(Uri requestURL, IWebConfiguration webConfig)
        {

            return AppUtil.GetAbsolutePath(webConfig.GetWebsiteRootPath() + requestURL.AbsolutePath);
        }

        public virtual void ParseRequestDocument(string docPath, HttpListenerContext context, IWebConfiguration webConfig)
        {
            HttpListenerResponse response = context.Response;

            if (!File.Exists(docPath))
            {
                LogUtil.PrintError("Cannot find file: " + docPath);
                response.StatusCode = 404;
                response.Close();
                return;
            }

            System.IO.Stream output = response.OutputStream;
            FileStream fs = null;

            try
            {
                fs = File.OpenRead(docPath);

                int read = 0;
                byte[] buffer = new byte[BUFFER_LEN];
                while ((read = fs.Read(buffer, 0, BUFFER_LEN)) > 0)
                {
                    output.Write(buffer, 0, read);
                }

            }
            catch (Exception e)
            {
                LogUtil.PrintError(e.Message);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }

                if (output != null)
                {
                    output.Close();
                }
            }
        }
    }
}
